/*
 * 
 */
package com.gidas.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import java.lang.Boolean;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.datepicker.client.DateBox;

import com.gidas.client.GetStopService;
import com.gidas.client.GetStopServiceAsync;


// TODO: Auto-generated Javadoc
/**
 * The Class AdminPanel.
 */
public class AdminPanel {

	/** The panel. */
	ScrollPanel panel = new ScrollPanel();

	/** The panel container. */
	AbsolutePanel panelContainer = new AbsolutePanel();

	/** The tabs panel. */
	TabPanel tabsPanel = new TabPanel();

	/** The public transport panel. */
	AbsolutePanel publicTransportPanel = new AbsolutePanel();

	/** The poi panel. */
	VerticalPanel poiPanel = new VerticalPanel();

	/** The xml load button. */
	Button xmlLoadButton = new Button();


	/** The now string. */
	String nowString = "";

	/** The seleted city string. */
	String seletedCityString = "";

	/** The grid data. */
	Object[][] gridData;

	/** The stops grid. */
	//GridPanel stopsGrid = new GridPanel();

	/** The stops number. */
	Label stopsNumber = new Label();

	/** The listeners. */
	private ArrayList<MapAdminListener> listeners = new ArrayList<MapAdminListener>();

	/** The xml stop load form. */
	final FormPanel xmlStopLoadForm = new FormPanel();

	/** The stop valid date string. */
	String stopValidDateString = "";

	/** The greeting service. */
	private final GetStopServiceAsync greetingService = GWT
			.create(GetStopService.class);

	/** The delete service. */
	private final DelStopServiceAsync deleteService = GWT
			.create(DelStopService.class);

	/** The Poi service. */
	private final PoiServiceAsync PoiService = GWT.create(PoiService.class);

	/** The new type panel. */
	VerticalPanel newTypePanel = null;

	/** The type list panel. */
	VerticalPanel typeListPanel = null;

	/** The object list panel. */
	VerticalPanel objectListPanel = null;

	/** The add poi type btn. */
	Button addPoiTypeBtn = null;

	/** The refresh poi type list btn. */
	Button refreshPoiTypeListBtn = null;

	/** The edit poi type list btn. */
	Button editPoiTypeListBtn = null;

	/** The del poi type list btn. */
	Button delPoiTypeListBtn = null;

	/** The object type list. */
	List<ObjectTypeSerializable> objectTypeList;

	/** The type list box. */
	ListBox typeListBox = null;

	// poi
	/** The poi table. */
	PoiTable poiTable = null;

	

	private int startRow = 0;
	private boolean showUnconfirmed = true;
	
	private List<String> filterList = new ArrayList<String>();
	public boolean showConfirmedPoi = true;
	private final NavBar tableNavigationBar = new NavBar();
	private final DockPanel navigation = new DockPanel();
	
	/**
	 * Creates the poi panel.
	 * 
	 * @return the vertical panel
	 */
	private VerticalPanel createPoiPanel() {
		VerticalPanel poiPanel = new VerticalPanel();

		VerticalPanel objectsPanel = new VerticalPanel();
		final DisclosurePanel newPoiTypePanel = new DisclosurePanel(
				"Naujas POI tipas");
		final DisclosurePanel poiTypeListPanel = new DisclosurePanel(
				"Visi POI tipai");
		final DisclosurePanel poiListPanel = new DisclosurePanel("Visi POI");
		newPoiTypePanel.addOpenHandler(new OpenHandler<DisclosurePanel>() {

			public void onOpen(OpenEvent<DisclosurePanel> event) {
				if (newTypePanel == null) {
					newTypePanel = new VerticalPanel();

					newTypePanel.add(new Label("ID"));
					final TextBox poiId = new TextBox();
					newTypePanel.add(poiId);

					newTypePanel.add(new Label("Pavadinimas"));
					final TextBox poiName = new TextBox();
					newTypePanel.add(poiName);

					newTypePanel.add(new Label("Laikas, min"));
					ArrayList<Integer> timeList = Constants.getTimeArray();

					final ListBox poiTime = new ListBox(false);
					for (Integer i : timeList) {
						poiTime.addItem("" + i);
					}

					newTypePanel.add(poiTime);

					addPoiTypeBtn = new Button("Sukurti", new ClickHandler() {

						public void onClick(ClickEvent event) {
							if (poiId.getText() == ""
									|| poiId.getText() == null
									|| poiName.getText() == ""
									|| poiName.getText() == null
									|| poiTime.getItemText(poiTime
											.getSelectedIndex()) == ""
									|| poiTime.getItemText(poiTime
											.getSelectedIndex()) == null) {
								Window.alert("Užpildykite visus laukus");
							} else {
								addPoiTypeBtn.setEnabled(false);
								addNewPoiType(poiId.getText(), poiName
										.getText(), poiTime.getItemText(poiTime
										.getSelectedIndex()));
							}

						}
					});
					newTypePanel.add(addPoiTypeBtn);

					newPoiTypePanel.add(newTypePanel);

				}

			}

		});

		poiTypeListPanel.addOpenHandler(new OpenHandler<DisclosurePanel>() {

			public void onOpen(OpenEvent<DisclosurePanel> event) {
				if (typeListPanel == null) {
					typeListPanel = new VerticalPanel();

					typeListBox = new ListBox();
					typeListBox.setVisibleItemCount(10);

					getPoiTypeList();
					typeListPanel.add(typeListBox);
					/*
					 * for (ObjectTypeSerializable o : objectTypeList) {
					 * typeListBox.addItem(o.getName(), o.getEncodedKey()); }
					 */
					// addItem
					// objectTypeList;
					refreshPoiTypeListBtn = new Button("Refresh",
							new ClickHandler() {
								public void onClick(ClickEvent event) {
									// typeListBox = new ListBox();
									// objectTypeList =
									getPoiTypeList();
								}
							});

					editPoiTypeListBtn = new Button("Edit", new ClickHandler() {
						public void onClick(ClickEvent event) {
							if (typeListBox.getSelectedIndex() == -1) {
								Window.alert("Pažymėkite objekto tipą!");
							} else {

								final DialogBox dialogBox = createTypeEditDialogBox(objectTypeList
										.get(typeListBox.getSelectedIndex()));
								dialogBox.setAnimationEnabled(true);
								dialogBox.center();
								dialogBox.show();
							}
						}
					});

					delPoiTypeListBtn = new Button("Del", new ClickHandler() {
						public void onClick(ClickEvent event) {
							if (typeListBox.getSelectedIndex() == -1) {
								Window.alert("Pažymėkite objekto tipą!");
							} else {

								final DialogBox dialogBox = createDelDialogBox(objectTypeList
										.get(typeListBox.getSelectedIndex()));
								dialogBox.setAnimationEnabled(true);
								dialogBox.center();
								dialogBox.show();
							}
						}
					});
					HorizontalPanel listButtonsPanel = new HorizontalPanel();
					listButtonsPanel.add(refreshPoiTypeListBtn);
					listButtonsPanel.add(editPoiTypeListBtn);
					listButtonsPanel.add(delPoiTypeListBtn);
					typeListPanel.add(listButtonsPanel);

					poiTypeListPanel.add(typeListPanel);
				}
			}

		});

		poiListPanel.addOpenHandler(new OpenHandler<DisclosurePanel>() {

			public void onOpen(OpenEvent<DisclosurePanel> event) {
				getPoiTypeList();
				if (objectListPanel == null) {
					objectListPanel = new VerticalPanel();

					// TODO add filters
					
					
					
				
					

					CheckBox showUnconfirmedPoiCheckBox = new CheckBox("Rodyti tik nepatvirtintus");
					showUnconfirmedPoiCheckBox.setValue(true);
					showUnconfirmedPoiCheckBox.addValueChangeHandler(new ValueChangeHandler<Boolean>(){

						public void onValueChange(final ValueChangeEvent<Boolean> event) {
							if(event.getValue())
							{
								//System.out.println("event.getValue()- " + event.getValue());
								showUnconfirmed = true;
							}
							else
							{
								showUnconfirmed = false;
							}
							startRow = 0;
							getPoi();
							
						}
						
					});
					objectListPanel.add(showUnconfirmedPoiCheckBox);
					poiTable = new PoiTable();
					poiTable.clear();
					//poiTable.
					
					poiTable.setWidth("40em");
					poiTable.setCellSpacing(5);
					poiTable.setCellPadding(3);
					poiTable.setBorderWidth(1);
					
					navigation.add(tableNavigationBar,DockPanel.NORTH);
					
					
					
					getPoi();

					
					
				    // FlexCellFormatter cellFormatter = poiTable
					// .getFlexCellFormatter();
					
					
					
					objectListPanel.add(poiTable);
					poiListPanel.add(objectListPanel);
				}

			}

		});

		objectsPanel.add(newPoiTypePanel);
		objectsPanel.add(poiTypeListPanel);
		objectsPanel.add(poiListPanel);
		poiPanel.add(objectsPanel);

		return poiPanel;

	}
	

	  public class NavBar extends Composite implements ClickHandler {

	    public final DockPanel bar = new DockPanel();
	    public final Button gotoFirst = new Button("&lt;&lt;", this);
	    public final Button gotoNext = new Button("&gt;", this);
	    public final Button gotoPrev = new Button("&lt;", this);
	    public final HTML status = new HTML();

	    public NavBar() {
	      initWidget(bar);
	      bar.setStyleName("navbar");
	      status.setStyleName("status");

	      HorizontalPanel buttons = new HorizontalPanel();
	      buttons.add(gotoFirst);
	      buttons.add(gotoPrev);
	      buttons.add(gotoNext);
	      bar.add(buttons, DockPanel.EAST);
	      bar.setCellHorizontalAlignment(buttons, DockPanel.ALIGN_RIGHT);
	      bar.add(status, DockPanel.CENTER);
	      bar.setVerticalAlignment(DockPanel.ALIGN_MIDDLE);
	      bar.setCellHorizontalAlignment(status, HasAlignment.ALIGN_RIGHT);
	      bar.setCellVerticalAlignment(status, HasAlignment.ALIGN_MIDDLE);
	      bar.setCellWidth(status, "100%");

	      // Initialize prev & first button to disabled.
	      //
	      gotoPrev.setEnabled(false);
	      gotoFirst.setEnabled(false);
	    }

	    public void onClick(ClickEvent event) {
	      Object source = event.getSource();
	      if (source == gotoNext) {
	        startRow += poiTable.getMaxRowCount();
	        //refresh();
	       
	        getPoi();
	      } else if (source == gotoPrev) {
	        startRow -= poiTable.getMaxRowCount();
	        if (startRow < 0) {
	          startRow = 0;
	        }
	        getPoi();
	      } else if (source == gotoFirst) {
	        startRow = 0;
	        getPoi();
	      }
	    }
	  }

	  
	public void setStatusText(String text) {
		tableNavigationBar.status.setText(text);
	}
	  
	/**
	 * Fill poi table.
	 * 
	 * @param list
	 *            the list
	 */
	private void fillPoiTable(List<ObjectSerializable> list) {
		/*
		if (poiTable == null) {

		}
		*/
		poiTable.clearTableRows();
		List<String> headers = new ArrayList<String>();
		headers.add("Tipas");
		headers.add("Pavadinimas");
		headers.add("Reitingas");
		poiTable.fillHeaders(headers);
		poiTable.setTableNavigationButtons(navigation);
		
		if (list != null) {
			
			System.out.println("rows count after cleaning = "+poiTable.getRowCount());

			for (final ObjectSerializable o : list) {
				ClickHandler confirmHandler = new ClickHandler() {
					public void onClick(ClickEvent event) {
						confirmObject(o);
						//System.out.println("JES!");
					}
				};
				ClickHandler deleteHandler = new ClickHandler() {
					public void onClick(ClickEvent event) {
						// TODO add delete
					}
				};
				ClickHandler editHandler = new ClickHandler() {
					public void onClick(ClickEvent event) {
						DialogBox dialogBox = createObjectEditDialogbox(o);
						dialogBox.setAnimationEnabled(true);
						dialogBox.center();
						dialogBox.show();

						// editObject(o);
					}
				};
				List<String> columns = new ArrayList<String>();
				//System.out.println(o.getObjectType() + ", " + o.getName() + ", " + o.getRating());
				columns.add(o.getObjectType());
				columns.add(o.getName());
				columns.add("" + o.getRating());

				poiTable.fillRow(columns, o.getConfirmed(), confirmHandler,
						deleteHandler, editHandler);
			}
		}
		else
		{
			//poiTable.clearTableRows();
		}
		

	}

	/**
	 * Confirm object.
	 * 
	 * @param object
	 *            the object
	 */
	private void confirmObject(ObjectSerializable object) {
		object.setConfirmed(true);
		PoiService.editPoi(object, new AsyncCallback<Boolean>() {

			public void onFailure(Throwable caught) {
				Window.alert(caught.toString());

			}

			public void onSuccess(Boolean result) {
				getPoi();

			}

		});
	}

	/**
	 * Edits the object.
	 * 
	 * @param object
	 *            the object
	 */
	private void editObject(ObjectSerializable object) {
		PoiService.editPoi(object, new AsyncCallback<Boolean>() {

			public void onFailure(Throwable caught) {
				Window.alert(caught.toString());

			}

			public void onSuccess(Boolean result) {
				Window.alert("" + result);

			}

		});
	}

	/**
	 * Creates the object edit dialogbox.
	 * 
	 * @param object
	 *            the object
	 * 
	 * @return the dialog box
	 */
	private DialogBox createObjectEditDialogbox(final ObjectSerializable object) {
		
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Objekto taisymas");
		VerticalPanel dialogContents = new VerticalPanel();
		dialogContents.setSpacing(4);
		dialogBox.setWidget(dialogContents);

		Grid grid = new Grid(9, 2);

		// adding components

		final TextBox poiName = new TextBox();
		poiName.setText(object.getName());
		grid.setWidget(0, 0, new Label("Pavadinimas:"));
		grid.setWidget(0, 1, poiName);
		

		final TextBox poiAddress = new TextBox();
		poiAddress.setText(object.getAddress());
		grid.setWidget(1, 0, new Label("Adresas:"));
		grid.setWidget(1, 1, poiAddress);
		

		// TODO tikrinima ar patvirtintas/nepatvirtintas
		ToggleButton confirmedBtn = new ToggleButton("Nepatvirtintas",
				"Patvirtintas");
		
		confirmedBtn.setDown(object.getConfirmed());
		grid.setWidget(2, 0, new Label("Patvirtintas:"));
		grid.setWidget(2, 1, confirmedBtn);

		final TextBox poiLat = new TextBox();
		poiLat.setText(""+object.getLat());
		final TextBox poiLng = new TextBox();
		poiLng.setText(""+object.getLng());
		grid.setWidget(3, 0, new Label("Koordinatės"));
		grid.setWidget(4, 0, new Label("Platuma:"));
		grid.setWidget(5, 0, new Label("Ilguma:"));
		grid.setWidget(4, 1, poiLat);
		grid.setWidget(5, 1, poiLng);

		
		
		
		final ListBox poiType = new ListBox(false);
		int i = 0;
		for(ObjectTypeSerializable o: objectTypeList)
		{
			
			poiType.addItem(o.getName(), o.getEncodedKey());
			if(o.getEncodedKey().compareToIgnoreCase(object.getObjectType()) == 0)
			{
				poiType.setSelectedIndex(i);
			}
			i++;
		}
		
		
		final ListBox poiTime = new ListBox(false);
		final ArrayList<Integer> timeList = Constants.getTimeArray();
		
		i = 0;
		for (int s : timeList) {
			// if(s.compareTo(anotherString))
			poiTime.addItem("" + s);
			if(s == object.getTakesTimeMinutes())
			{
				poiTime.setSelectedIndex(i);
			}
			i++;
		}
		
		//TODO perdaryt
		final ListBox poiRating = new ListBox(false);
		for(int j = 0; j < 6; j++)
		{
			poiRating.addItem("" + j);
			if(j == object.getRating())
			{
				poiRating.setSelectedIndex(j);
			}
		}
		
		grid.setWidget(6, 0, new Label("Tipas:"));
		grid.setWidget(6, 1, poiType);
		grid.setWidget(7, 0, new Label("Laikas, min:"));
		grid.setWidget(7, 1, poiTime);
		grid.setWidget(8, 0, new Label("Įvertinimas:"));
		grid.setWidget(8, 1, poiRating);

		dialogContents.add(grid);
		
		
		
		
		dialogContents.add(new Label("Objekto aprašymas:"));
		final TextArea area = new TextArea();
		area.setText(object.getDescription());
		area.setWidth("300");
		area.setHeight("150");
		dialogContents.add(area);

		HorizontalPanel buttonsPanel = new HorizontalPanel();

		Button closeButton = new Button("Close", new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
			}
		});
		Button editButton = new Button("Taisyti", new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
			}
		});
		buttonsPanel.add(closeButton);
		buttonsPanel.add(editButton);
		dialogContents.add(buttonsPanel);
		return dialogBox;
	}

	/**
	 * Gets the poi.
	 * 
	 * @param filterList
	 *            the filter list
	 * @param showOnlyConfirmed
	 *            the show only confirmed
	 * @param rangeBegin
	 *            the range begin
	 * @param rangeEnd
	 *            the range end
	 * 
	 * @return the poi
	 */

	
	
	private void getPoi()
	{
		
		tableNavigationBar.gotoFirst.setEnabled(false);
		tableNavigationBar.gotoPrev.setEnabled(false);
		tableNavigationBar.gotoNext.setEnabled(false);
		setStatusText("Palaukite...");
		System.out.println("filterList - "+filterList+", showConfirmedPoi - " + showConfirmedPoi + ", startRow - "+ startRow + ", poiTable.getMaxRowCount() - "+poiTable.getMaxRowCount());
		PoiService.getPoiService(filterList, !showUnconfirmed, startRow,
				poiTable.getMaxRowCount(), new AsyncCallback<List<ObjectSerializable>>() {

					public void onFailure(Throwable caught) {
						Window.alert(caught.toString());

						tableNavigationBar.gotoFirst.setEnabled(true);
						tableNavigationBar.gotoPrev.setEnabled(true);
						tableNavigationBar.gotoNext.setEnabled(true);
						setStatusText("Klaida..:/");
					}

					public void onSuccess(List<ObjectSerializable> result) {
						boolean isLastPage = false;
						if(result.size() < poiTable.getMaxRowCount())
						{
							isLastPage = true;
						}
						tableNavigationBar.gotoNext.setEnabled(!isLastPage);
						tableNavigationBar.gotoFirst.setEnabled(startRow > 0);
					    tableNavigationBar.gotoPrev.setEnabled(startRow > 0);
					    setStatusText((startRow + 1) + " - " + (startRow + result.size()));
						if (result.isEmpty() || result == null) {
							//Window.alert("Objektų nerasta...");
							fillPoiTable(null);
							poiTable.setTableNavigationButtons(navigation);
							setStatusText("Objektų nerasta...");
							tableNavigationBar.gotoFirst.setEnabled(false);
							tableNavigationBar.gotoPrev.setEnabled(false);
							tableNavigationBar.gotoNext.setEnabled(false);

						} else {
							fillPoiTable(result);
						}

					}
				});
	}

	/**
	 * Creates the type edit dialog box.
	 * 
	 * @param type
	 *            the type
	 * 
	 * @return the dialog box
	 */
	private DialogBox createTypeEditDialogBox(final ObjectTypeSerializable type) {
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Objekto tipo taisymas");

		VerticalPanel dialogContents = new VerticalPanel();

		dialogContents.setSpacing(4);
		dialogBox.setWidget(dialogContents);

		dialogContents.add(new Label("ID"));
		final TextBox poiId = new TextBox();
		poiId.setEnabled(false);
		poiId.setText(type.getEncodedKey());
		dialogContents.add(poiId);

		dialogContents.add(new Label("Pavadinimas"));
		final TextBox poiName = new TextBox();
		poiName.setText(type.getName());
		dialogContents.add(poiName);

		dialogContents.add(new Label("Laikas, min"));

		ArrayList<Integer> timeList = Constants.getTimeArray();
		final ListBox poiTime = new ListBox(false);
		for (int s : timeList) {
			poiTime.addItem("" + s);
		}

		dialogContents.add(poiTime);

		ArrayList<String> list = new ArrayList<String>();
		list.add("10");

		// Add a close button at the bottom of the dialog
		Button closeButton = new Button("Close", new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
			}
		});
		Button editButton = new Button("Taisyti", new ClickHandler() {
			public void onClick(ClickEvent event) {
				ObjectTypeSerializable editedType = new ObjectTypeSerializable();
				editedType.setEncodedKey(type.getEncodedKey());
				editedType.setName(poiName.getText());
				editedType.setTakesTimeMinutes(Integer.parseInt(poiTime
						.getItemText(poiTime.getSelectedIndex())));
				editPoiType(editedType);
				dialogBox.hide();
			}
		});
		HorizontalPanel buttonsPanel = new HorizontalPanel();
		buttonsPanel.add(closeButton);
		buttonsPanel.add(editButton);

		dialogContents.add(buttonsPanel);

		return dialogBox;
	}

	/**
	 * Creates the del dialog box.
	 * 
	 * @param type
	 *            the type
	 * 
	 * @return the dialog box
	 */
	private DialogBox createDelDialogBox(final ObjectTypeSerializable type) {
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Trinti?");

		VerticalPanel dialogContents = new VerticalPanel();

		dialogContents.setSpacing(4);
		dialogContents
				.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		dialogBox.setWidget(dialogContents);

		dialogContents.add(new Label("Ar tikrai norite trinti?"));

		Button closeButton = new Button("Ne", new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
			}
		});
		Button delButton = new Button("Trinti", new ClickHandler() {
			public void onClick(ClickEvent event) {
				// trinti
				ObjectTypeSerializable deleteType = new ObjectTypeSerializable();
				deleteType.setEncodedKey(type.getEncodedKey());
				delPoiType(deleteType);
				System.out.println("triiiinam....");
				dialogBox.hide();
			}
		});
		HorizontalPanel buttonsPanel = new HorizontalPanel();
		buttonsPanel.add(closeButton);
		buttonsPanel.add(delButton);

		dialogContents.add(buttonsPanel);

		return dialogBox;
	}

	/**
	 * Fill type list box.
	 */
	private void fillTypeListBox() {
		if(typeListBox == null)
		{
			typeListBox = new ListBox();
		}
		typeListBox.clear();
		for (ObjectTypeSerializable o : objectTypeList) {

			String name = o.getName() + " - " + o.getTakesTimeMinutes()
					+ " min";
			typeListBox.addItem(name, o.getEncodedKey());

			System.out.println(o.getName());

		}
	}

	/**
	 * Edits the poi type.
	 * 
	 * @param objectType
	 *            the object type
	 */
	private void editPoiType(ObjectTypeSerializable objectType) {
		PoiService.editPoiTypeService(objectType, new AsyncCallback<Boolean>() {

			public void onFailure(Throwable caught) {
				Window.alert(caught.toString());

			}

			public void onSuccess(Boolean result) {
				Window.alert("Pataisė!");
				getPoiTypeList();
				// refresh
			}
		});
	}

	/**
	 * Del poi type.
	 * 
	 * @param objectType
	 *            the object type
	 */
	private void delPoiType(ObjectTypeSerializable objectType) {
		PoiService.delPoiTypeService(objectType, new AsyncCallback<Boolean>() {

			public void onFailure(Throwable caught) {
				Window.alert(caught.toString());

			}

			public void onSuccess(Boolean result) {
				Window.alert("Ištrynė!");
				getPoiTypeList();
				// refresh
			}
		});
	}

	/**
	 * Gets the poi type list.
	 * 
	 * @return the poi type list
	 */
	private void getPoiTypeList() {

		PoiService
				.getPoiTypeService(new AsyncCallback<List<ObjectTypeSerializable>>() {

					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						Window.alert(caught.toString());
						addPoiTypeBtn.setEnabled(true);
					}

					public void onSuccess(List<ObjectTypeSerializable> result) {

						objectTypeList = new ArrayList<ObjectTypeSerializable>();
						objectTypeList = result;
						fillTypeListBox();
					}

				});

	}

	/**
	 * Adds the new poi type.
	 * 
	 * @param poiId
	 *            the poi id
	 * @param poiName
	 *            the poi name
	 * @param poiTime
	 *            the poi time
	 */
	private void addNewPoiType(String poiId, String poiName, String poiTime) {
		ObjectTypeSerializable objectType = new ObjectTypeSerializable(poiId,
				poiName, Integer.parseInt(poiTime));
		PoiService.addPoiTypeService(objectType, new AsyncCallback<Boolean>() {

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				Window.alert(caught.toString());
				addPoiTypeBtn.setEnabled(true);
			}

			public void onSuccess(Boolean result) {
				if (result) {
					Window.alert("Įdėjo!");
					if (typeListBox != null) {
						getPoiTypeList();
					}

				} else {
					Window.alert("Toks POI tipas jau yra!");
				}
				addPoiTypeBtn.setEnabled(true);
			}

		});
	}

	// private void

	/**
	 * Instantiates a new admin panel.
	 */
	public AdminPanel() {
		
		Button back = new Button("Atgal į žemėlapį", new ClickHandler() {
			public void onClick(ClickEvent event) {
				onBackToMapAttempt();
			}

		});

		panelContainer.add(back);
		panelContainer.add(tabsPanel);
		panel.add(panelContainer);

		panel.setPixelSize(Window.getClientWidth(),
				Window.getClientHeight() - 100);
		tabsPanel.setPixelSize(Window.getClientWidth(), Window
				.getClientHeight() - 80);
		publicTransportPanel.setPixelSize(Window.getClientWidth(), Window
				.getClientHeight() - 80);
		poiPanel.setPixelSize(Window.getClientWidth(),
				Window.getClientHeight() - 80);
		Window.addResizeHandler(new ResizeHandler() {

			public void onResize(ResizeEvent event) {

				panel.setPixelSize(Window.getClientWidth(), Window
						.getClientHeight() - 100);
				tabsPanel.setPixelSize(Window.getClientWidth(), Window
						.getClientHeight() - 80);
				publicTransportPanel.setPixelSize(Window.getClientWidth(),
						Window.getClientHeight() - 80);
				poiPanel.setPixelSize(Window.getClientWidth(), Window
						.getClientHeight() - 80);

				// TODO Auto-generated method stub

			}

		});
		String chooseCityText = "Pasirinkite miestą:";
		HorizontalPanel chooseCityPanel = new HorizontalPanel();
		ListBox dropBox = new ListBox(false);
		dropBox.addItem("Kaunas");

		chooseCityPanel.add(new Label(chooseCityText));
		chooseCityPanel.add(dropBox);

		VerticalPanel stopsAndRoutesPanel = new VerticalPanel();

		DisclosurePanel stopsPanel = new DisclosurePanel("Stotelės");
		DisclosurePanel routesPanel = new DisclosurePanel("Maršrutai");

		stopsAndRoutesPanel.add(stopsPanel);
		stopsAndRoutesPanel.add(routesPanel);

		String stopsNumberText = "Stotelių skaičius: ";
		Label stopsNumberLabel = new Label(stopsNumberText);

		DateBox stopValidDateBox = new DateBox();
		stopValidDateBox.addValueChangeHandler(new ValueChangeHandler<Date>() {
			public void onValueChange(ValueChangeEvent<Date> event) {
				Date date = event.getValue();
				stopValidDateString = DateTimeFormat.getMediumDateFormat()
						.format(date);

			}
		});
		Date now = new Date();
		int nowYear = now.getYear() + 1900;
		String nowYearString = Integer.toString(nowYear);

		// to get format yyyy/mm/dd not yyyy/m/dd
		int nowMonth = now.getMonth() + 1;
		String nowMonthString = "";
		if (nowMonth > 9) {
			nowMonthString = Integer.toString(nowMonth);
		} else {
			nowMonthString = "0" + Integer.toString(nowMonth);
		}

		int nowDay = now.getDate();
		String nowDayString = "";
		if (nowDay > 9) {
			nowDayString = Integer.toString(nowDay);
		} else {
			nowDayString = "0" + Integer.toString(nowDay);
		}

		nowString = nowYearString + "." + nowMonthString + "." + nowDayString;
		seletedCityString = dropBox.getItemText(dropBox.getSelectedIndex());

		stopValidDateBox.setValue(now);

		VerticalPanel stopsNumberAndListPanel = new VerticalPanel();

		stopsNumberAndListPanel.add(stopsNumberLabel);
		stopsNumberAndListPanel.add(stopsNumber);

		//getStopsGrid();

		//Panel panelTmp = new Panel();
	/*
		Button getStopsButton = new Button("Užpildyti lentelę",
				new ClickHandler() {
					public void onClick(ClickEvent event) {
						getStopData();
					}
				});
		Button delAllStopsButton = new Button("Trinti viska!",
				new ClickHandler() {
					public void onClick(ClickEvent event) {
						delAllStops();
					}
				});

		panelTmp.add(getStopsButton);
		panelTmp.add(delAllStopsButton);
		
		panelTmp.add(stopsGrid);
		stopsNumberAndListPanel.add(grid);
		
		
		//
		stopsNumberAndListPanel.add(panelTmp);
		*/
		stopsPanel.add(stopsNumberAndListPanel);

		publicTransportPanel.add(chooseCityPanel);

		stopsXmlLoad();
		publicTransportPanel.add(xmlStopLoadForm);

		publicTransportPanel.add(stopsAndRoutesPanel);

		tabsPanel.add(publicTransportPanel, "Viešasis transportas");
		tabsPanel.add(createPoiPanel(), "POI");

		tabsPanel.selectTab(0);

	}

	/**
	 * Adds the sign in listener.
	 * 
	 * @param listener
	 *            the listener
	 */
	public void addSignInListener(MapAdminListener listener) {
		listeners.add(listener);
	}

	/**
	 * Removes the sign in listener.
	 * 
	 * @param listener
	 *            the listener
	 */
	public void removeSignInListener(MapAdminListener listener) {
		listeners.remove(listener);
	}

	/**
	 * On back to map attempt.
	 */
	public void onBackToMapAttempt() {
		for (Iterator<MapAdminListener> it = listeners.iterator(); it.hasNext();) {
			MapAdminListener listener = (MapAdminListener) it.next();
			listener.onChangeLayout();
		}
	}

	/**
	 * Stops xml load.
	 */
	public void stopsXmlLoad() {
		xmlStopLoadForm.setAction("/gm/xmlUploadFormHandler");

		// Because we're going to add a FileUpload widget, we'll need to set the
		// form to use the POST method, and multipart MIME encoding.
		xmlStopLoadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
		xmlStopLoadForm.setMethod(FormPanel.METHOD_POST);

		VerticalPanel formPanel = new VerticalPanel();
		xmlStopLoadForm.setWidget(formPanel);

		FileUpload xmlUpload = new FileUpload();

		xmlUpload.setName(nowString + "." + seletedCityString);

		formPanel.add(xmlUpload);

		xmlLoadButton = new Button("Naujas XML", new ClickHandler() {
			public void onClick(ClickEvent event) {
				xmlStopLoadForm.submit();
			}
		});

		formPanel.add(xmlLoadButton);

		xmlStopLoadForm.addSubmitHandler(new FormPanel.SubmitHandler() {
			public void onSubmit(SubmitEvent event) {
				xmlLoadButton.setEnabled(false);
				// add loading gif
			}
		});

		xmlStopLoadForm
				.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
					public void onSubmitComplete(SubmitCompleteEvent event) {
						xmlLoadButton.setEnabled(true);
						Window.alert(event.getResults());
						// remove loading gif
					}
				});
	}

	
	/**
	 * Gets the stops grid.
	 * 
	 * @return the stops grid
	 */
	/*
	private void getStopsGrid() {
		RecordDef recordDef = new RecordDef(new FieldDef[] {
				new StringFieldDef("nativeId"), new StringFieldDef("name"),
				new StringFieldDef("street"), new StringFieldDef("lat"),
				new StringFieldDef("lng") });
		// true - fill object array with empty object
		fillStopsGrid(true);

		MemoryProxy proxy = new MemoryProxy(gridData);

		ArrayReader reader = new ArrayReader(recordDef);
		Store store = new Store(proxy, reader);
		store.load();
		stopsGrid.setStore(store);

		ColumnConfig[] columns = new ColumnConfig[] {
				// column ID is company which is later used in
				// setAutoExpandColumn
				new ColumnConfig("ID", "nativeId", 35, true, null, "nativeId"),
				new ColumnConfig("Pavadinimas", "name", 160, true),
				new ColumnConfig("Gatvė", "street", 160),
				new ColumnConfig("Lat", "lat", 60),
				new ColumnConfig("Lng", "lng", 60, true) };
		ColumnModel columnModel = new ColumnModel(columns);

		stopsGrid.setColumnModel(columnModel);
		stopsGrid.setFrame(true);
		stopsGrid.setStripeRows(true);
		stopsGrid.setAutoExpandColumn("nativeId");

		stopsGrid.setHeight(350);
		stopsGrid.setWidth(600);
		stopsGrid.setTitle("Stotelės");

	}
*/
	
	/**
	 * Del all stops.
	 */
	
	
	private void delAllStops() {
		deleteService.delStopService(new AsyncCallback<Boolean>() {

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				Window.alert(caught.toString());

			}

			public void onSuccess(Boolean result) {
				// TODO Auto-generated method stub
				Window.alert("Pavyko? -" + result);

			}

		});
	}

	/**
	 * Gets the stop data.
	 * 
	 * @return the stop data
	 */
	/*
	private void getStopData() {
		greetingService
				.getStopService(new AsyncCallback<List<StopsSerializable>>() {
					public void onFailure(Throwable caught) {
						System.out.println(caught.toString());
					}

					public void onSuccess(List<StopsSerializable> result) {
						int resultSize = result.size();
						stopsNumber.setText("" + resultSize);
						Object[][] objectsArray = new Object[resultSize][5];
						int i = 0;
						for (StopsSerializable s : result) {
							String idString = Long.toString(s.getNativeId());
							String nameString = s.getName();
							String streetString = s.getStreet();
							String latString = s.getLat();
							String lngString = s.getLng();
							objectsArray[i][0] = idString;
							objectsArray[i][1] = nameString;
							objectsArray[i][2] = streetString;
							objectsArray[i][3] = latString;
							objectsArray[i][4] = lngString;
							i++;
						}
						gridData = objectsArray;
						fillStopsGrid(false);
					}
				});
	}
*/
	/**
	 * Fill stops grid.
	 * 
	 * @param gridEmpty
	 *            the grid empty
	 */
	/*
	private void fillStopsGrid(boolean gridEmpty) {
		if (gridEmpty) {
			gridData = new Object[][] {};

		}

		RecordDef recordDef = new RecordDef(new FieldDef[] {
				new StringFieldDef("nativeId"), new StringFieldDef("name"),
				new StringFieldDef("street"), new StringFieldDef("lat"),
				new StringFieldDef("lng")
		// new DateFieldDef("lastChanged", "n/j h:ia")
				});

		ColumnConfig[] columns = new ColumnConfig[] {
				// column ID is company which is later used in
				// setAutoExpandColumn
				new ColumnConfig("ID", "nativeId", 35, true, null, "nativeId"),
				new ColumnConfig("Pavadinimas", "name", 160, true),
				new ColumnConfig("Gatvė", "street", 160, true),
				new ColumnConfig("Lat", "lat", 60, true),
				new ColumnConfig("Lng", "lng", 60, true) };
		ColumnModel columnModel = new ColumnModel(columns);

		MemoryProxy proxy = new MemoryProxy(gridData);

		ArrayReader reader = new ArrayReader(recordDef);
		Store store = new Store(proxy, reader);
		store.load();
		if (stopsGrid.getStore() == null) {
			stopsGrid.setStore(store);
		} else
			stopsGrid.reconfigure(store, columnModel);
	}
*/
	/**
	 * Gets the panel.
	 * 
	 * @return the panel
	 */
	public ScrollPanel getPanel() {
		return this.panel;
	}

}
